package com.nulldev.util.encoding;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.other.ArrayUtils;

public class ObjectUtils {

	public static <T> byte[] toSerial(final T object)  {
		try {
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
			final ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			final byte[] data = baos.toByteArray();
			baos.close();
			return data;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static <T> T fromSerial(final byte[] data) {
		try {
			final ByteArrayInputStream bais = new ByteArrayInputStream(data);
			final ObjectInputStream obis = new ObjectInputStream(bais);
			final T object = (T) obis.readObject();
			obis.close();
			return object;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void safePrint(final Object a) {
		try { 
			ArrayUtils.println((String[]) a);
		}catch (Exception e) {
			JVMUtil.async_println(a);
		} 
	}
}
